<template>
    <section v-loading="firstLoading" style="height:100%;">
        <div class="work-search-wrap">
            <el-select
                class="search-select"
                v-model="state"
                :placeholder="$t('common.placeholder.selectTaskState')"
                multiple     
            >
            <el-option
                v-for="item in taskStatesOpitos"
                :key="item.value"
                :label="item.text"
                :value="item.value"
            >
            </el-option>
            </el-select>
            <div>
                <el-button type="primary" @click="onSearch">{{ $t('common.base.search') }}</el-button>
                <el-button @click="reset">{{ $t('common.base.reset') }}</el-button>
            </div>

        </div>
        <el-table
            stripe
            border
            :data="dataList"
            @sort-change="sortChange"
            v-loading="loading"
            v-if="dataList.length"
        >

            <el-table-column prop="taskNo" :label="$t('common.label.taskNo')" show-overflow-tooltip>
                <template slot-scope="{row}">
                    <el-button 
                        type="text" 
                        @click="openNewTab(row)"
                    >
                        {{row.taskNo}}
                    </el-button>
                </template>
            </el-table-column>

            <el-table-column prop="templateName" :label="$t('common.label.taskTemplate')" show-overflow-tooltip />
            
            <el-table-column prop="customerEntity.name"  sortable :label="$t('common.label.customer')" show-overflow-tooltip />

            <el-table-column prop="products" :label="$t('common.label.product')" show-overflow-tooltip :formatter="formatterProductst" />

            <el-table-column prop="state" :label="$t('common.label.status')" show-overflow-tooltip >
                <template slot-scope="{row}">
                    <span v-if="row.attribute && row.attribute.lastPassedNodeStateName">
                       {{row.attribute.lastPassedNodeStateName}}
                    </span>
                    <span v-else>
                       {{formatterState(row) || ''}}
                    </span>
                 </template>
            </el-table-column>

            <el-table-column prop="createTime" sortable width="150" :label="$t('common.label.createTime')" show-overflow-tooltip>
                <template slot-scope="{row}">
                    {{ row.createTime | fmt_datetime }}
                </template>
            </el-table-column>

            <el-table-column prop="completeTime" :label="$t('common.label.finishTime')" show-overflow-tooltip>
                <template slot-scope="{row}">
                    {{ row.completeTime | fmt_datetime }}
                </template>
            </el-table-column>

            <el-table-column prop="evaluateContent" :label="$t('common.label.customerEvaluation')" show-overflow-tooltip />

        </el-table>

         <NoAuth v-if="!firstLoading && !dataList.length"/>

        <Pagination 
            v-model="page"
            @handleSizeChange="initData"
            @handleCurrentChange="initData">
        </Pagination>
    </section>
</template>

<script>
// 翻页组件
import Pagination from '../Pagination.vue'

// 暂无数据组件
import NoAuth from '../NoAuth.vue'

import * as HomeApi from "@src/api/HomeApi";

import {switchState} from "../../util";
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import { openAccurateTab } from '@src/util/platform'
/* model */
import { Inquire } from '@src/modules/task/list/TaskFieldModel.js'; 

export default {
    name:'tabPaneWorkOrder',

    data(){
        return {
            loading:false,

            // 用于解决第一次进入直接展示暂无数据再展示数据的bug
            firstLoading:true,
            
            page:{
                total:0,
                pageSize:10,
                pageNum:1
            },
            dataList:[],
            sortModel: null, // 排序
            state:[]
        }
    },

    props:{
        user:{
            type:Object,
            required:true
        },
        userId:[String,Number]
    },

    components:{
        Pagination,
        NoAuth
    },
    computed:{
        taskStatesOpitos() {
            let option = []
            Inquire.map(field =>{
                const { fieldName,setting } = field
                if(fieldName == "state"){
                    option = setting.dataSource || []
                }
            })
         return option;
        },

    },

    mounted(){
        this.initData();
    },

    methods:{
        onSearch() {
            this.page.pageNum = 1;
            this.initData();
        },
         /** 重置*/
        reset() {
            this.state = [];
            this.page.pageNum = 1;
            this.initData();
        },
        /** 排序变化*/
        sortChange(option) {
            const sortTableMap = {
            'customerEntity.name': 'customerName',
            'createTime':'createTime'  
            }
            const { prop, order } = option;
            if (!order) {
                this.sortModel = null;
                return  this.initData();
            }
            this.sortModel = {
                direction: order === 'ascending' ? 'ASC' : 'DESC',
                property: sortTableMap[prop]
            }
            this.page.pageNum = 1;
            this.initData();
        },
        
        initData(){
            const { pageSize, pageNum } = this.page;

            const params = {
                pageSize,
                page:pageNum,
                executor:this.userId,
                queryCreateHalf: true // 查工单列表草稿状态必传
            }
            // 如果有排序
            if(this.sortModel) {
                params.sorts = [this.sortModel];
            }
            // 工单状态参数  
            if(this.state.length >0) {
                params.systemConditions = [
                    {
                        operator: "in",
                        property: "state",
                        inValue: this.state
                    }
                ]
            }
            this.loading = true;
            HomeApi.getTaskList(params).then((res) => {
                const { data:{ list = [],total = 0 }, status } = res;
                this.dataList = list || [];
                this.page.total = total;

                this.loading = false;
                this.firstLoading = false
            }).catch(e=>{
                this.loading = false;
                this.firstLoading = false
                console.error('fetch task caught e', e)
            })                                                                        
        },

        
        openNewTab({taskUUID, taskNo}){
            const fromId = window.frameElement.getAttribute('id');

            // this.$platform.openTab({
            //     id: `task_view_${taskUUID}`,
            //     title: `工单${taskNo}`,
            //     close: true,
            //     url: `/task/view/${taskUUID}?noHistory=1`,
            //     fromId
            // });
            openAccurateTab({
                type: PageRoutesTypeEnum.PageTaskView,
                key: taskUUID,
                titleKey: taskNo,
                params: 'noHistory=1',
                fromId
            })
        },

        formatterState(row, column) {
            return switchState(row.state);
        },

        formatterProductst({products=[]}){

            // if(typeof productTypeList === 'string') return productTypeList;

            let product = [];

            if(Array.isArray(products)){
                products.map(item =>{
                    product.push(item.name)
                })
            }

            return product.join(',')
        }
    }
}
</script>

<style lang="scss" scoped>

.el-table{
    border-top:1px solid #E8E8E8;
    border-left:1px solid #E8E8E8;
}
.work-search-wrap {
    display:flex;
    justify-content: flex-start;
    margin: 0 0 12px;
    .search-select {
        width: 300px;
        margin-right: 10px;
    }

}
</style>
